<?php

namespace seecms\db\traits;

use seecms\db\SeeDbRaw;

trait SeeDbPolymerization
{
    /**
     * COUNT查询
     *
     * @param string|SeeDbRaw $field 字段名
     * @return integer|string   结果集
     */
    public function count($field = '*')
    {
        if ($field instanceof SeeDbRaw) {
            $field = $field->getValue();
        }
        $result = $this->field('COUNT(' . $field . ') AS total')->select();
        if ($result instanceof \PDOStatement || is_string($result)) {
            // 返回PDOStatement对象或者查询语句
            return $result;
        }
        return $result[0]['total'] ?? 0;
    }

    /**
     * SUM查询
     *
     * @param string|SeeDbRaw $field 字段名
     * @return float|integer    结果集
     */
    public function sum($field)
    {
        if ($field instanceof SeeDbRaw) {
            $field = $field->getValue();
        }
        $result = $this->field('SUM(' . $field . ') AS sum')->select();
        if ($result instanceof \PDOStatement || is_string($result)) {
            // 返回PDOStatement对象或者查询语句
            return $result;
        }

        return $result[0]['sum'] ?? 0;
    }

    /**
     * MIN查询
     *
     * @param string|SeeDbRaw $field 字段名
     * @return mixed  结果集
     */
    public function min($field)
    {
        if ($field instanceof SeeDbRaw) {
            $field = $field->getValue();
        }
        $result = $this->field('MIN(' . $field . ') AS min')->select();
        if ($result instanceof \PDOStatement || is_string($result)) {
            return $result;
        }

        return $result[0]['min'] ?? false;
    }

    /**
     * MAX查询
     *
     * @param string|SeeDbRaw $field 字段名
     * @return mixed    结果集
     */
    public function max($field)
    {
        if ($field instanceof SeeDbRaw) {
            $field = $field->getValue();
        }

        $result = $this->field('MAX(' . $field . ') AS max')->select();
        if ($result instanceof \PDOStatement || is_string($result)) {
            return $result;
        }

        return $result[0]['max'] ?? null;
    }

    /**
     * AVG查询
     *
     * @param string|SeeDbRaw $field 字段名
     * @return mixed    结果集
     */
    public function avg($field)
    {
        if ($field instanceof SeeDbRaw) {
            $field = $field->getValue();
        }

        $result = $this->field('AVG(' . $field . ') AS avg')->select();
        if ($result instanceof \PDOStatement || is_string($result)) {
            return $result;
        }

        return $result[0]['avg'] ?? null;
    }
}